package servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import pojo.FoodType;
import dto.MItem;
import service.FoodListManager;
import service.MListManager;
import service.factory.FoodListManagerFactory;
import service.factory.MListManagerFactory;
import util.JacksonUtil;

public class RequestMListServlet extends BaseServlet {
	private static final long serialVersionUID = 1L;

	private MListManager manager;
	private FoodListManager flManager;

	public RequestMListServlet() {
		super();
		manager = MListManagerFactory.getInstance();
		flManager = FoodListManagerFactory.getInstance();
	}

	@Override
	public void execute(HttpServletRequest req, HttpServletResponse resp)
			throws Exception {

		///html 的请求
		String searchName = req.getParameter("searchName");
		String searchId = req.getParameter("searchId");

		
		if (searchName != null && searchName.trim().length() > 0) {
			List<MItem> mlist = (List<MItem>) req.getSession().getAttribute(
					"mlist");
			List<MItem> resList = new ArrayList<MItem>();
			for(int i=0;i<mlist.size();i++){
				MItem it = mlist.get(i);
				if (it.getStoreName().contains(searchName)) {
					resList.add(it);
				}
			}
			req.getSession().setAttribute("mlist", resList);
		}

		if (searchId != null && searchId.trim().length() > 1) {// length ==1 all

			List<String> midList = this.flManager
					.findAllMerchantIdByFoodTypeId(searchId);
			List<MItem> mlist = (List<MItem>) req.getSession().getAttribute(
					"mlist");
			List<MItem> resList = new ArrayList<MItem>();
			for (int i=0;i<mlist.size();i++) {
				MItem item = mlist.get(i);
				for (String mid : midList) {
					if (item.getId().equals(mid)) {
						resList.add(item);
					}
				}
			}
			req.getSession().setAttribute("mlist", resList);
		}

		// 转向
		// req.setAttribute("mlist", resList);
//		req.setAttribute("searchName", searchName);
//		req.setAttribute("curType", searchId);
//		req.getRequestDispatcher("home.jsp").forward(req, resp);

		
		// 转回JSON串
		// 发送回给客户端
		PrintWriter writer = resp.getWriter();
		String jsonStr = JacksonUtil.fromObjectToJson(req.getSession().getAttribute("mlist"));
		System.out.println(jsonStr);
		writer.write(jsonStr);
		
		writer.close();
	}
	
}
